//
//  DFPageHeadView.m
//  Pods
//
//  Created by rujia chen on 17/4/12.
//
//

#import "DFPageHeadView.h"
#import "Masonry.h"
#import "UIView+DFExtension.h"
#import "DFKitMarco.h"
#import "UIColor+DFExtension.h"

@interface DFPageHeadView(){
    MASConstraint *_scrollContentViewEdgeConstraint;
    MASConstraint *_scrollContentViewCenterXConstraint;
    
    MASConstraint *_indicatorWidthConstraint;
    MASConstraint *_indicatorCenterXConstraint;
}

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) UIView *contentView;

@property (nonatomic, strong) NSMutableArray <UIButton *>*buttons;

@property (nonatomic, strong) UIVisualEffectView *visualView;

@end

@implementation DFPageHeadView

- (instancetype)init {
    if (self = [super init]) {
        [self addSubview:self.scrollView];
        [self.scrollView addSubview:self.contentView];
        [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.equalTo(self.scrollView);
            _scrollContentViewEdgeConstraint = make.left.right.equalTo(self.scrollView);
            make.height.equalTo(self.scrollView);
            _scrollContentViewCenterXConstraint = make.centerX.equalTo(self.scrollView);
        }];
        [_scrollContentViewEdgeConstraint deactivate];
        [_scrollContentViewCenterXConstraint deactivate];
        
        [self.indicatorView df_setIntrinsicContentSizeBlock:^CGSize(UIView *view) {
            return CGSizeMake(UIViewNoIntrinsicMetric, 2);
        }];
        [self.contentView addSubview:self.indicatorView];
        
        [self.indicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
            _indicatorWidthConstraint = make.width.equalTo(@20);
            make.bottom.equalTo(self.contentView);
        }];
        
        self.backgroundColor = [UIColor clearColor];
    }
    
    return self;
}

- (void)setBackgroundVisulEffect:(UIVisualEffect *)backgroundVisulEffect {
    _backgroundVisulEffect = backgroundVisulEffect;
    [self.visualView setEffect:backgroundVisulEffect];
}

- (void)setTitles:(NSMutableArray<NSString *> *)titles {
    for (UIView *subView in self.contentView.subviews) {
        if ([subView isKindOfClass:[UIButton class]]) {
            [subView removeFromSuperview];
        }
    }
    
    for (NSString *title in titles) {
        UIButton *button = [self createButtonWithTitle:title];
        [button addTarget:self action:@selector(tapAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:button];
        [self.buttons addObject:button];
    }
}

- (void)setBackgroundView:(UIToolbar *)backgroundView {
    if (_backgroundView) {
        [_backgroundView removeFromSuperview];
    }
    _backgroundView = backgroundView;
    [self addSubview:_backgroundView];
    [_backgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    [self sendSubviewToBack:_backgroundView];
}

- (void)tapAction:(UIButton *)button {
    NSInteger index = [self.buttons indexOfObject:button];
    if (self.tabClickBlock) {
        self.tabClickBlock(index);
    }
}

- (void)setInsets:(UIEdgeInsets)insets {
    _insets = insets;
}

- (void)updateConstraints {
    [super updateConstraints];
    CGFloat sumWidth = 0;
    sumWidth += self.titleButtonSpacing;
    for (UIButton *button in self.buttons) {
        sumWidth += ([button intrinsicContentSize].width + self.titleButtonSpacing);
    }
    
    BOOL needScrollFlag = (sumWidth >= DF_SCREEN_WIDTH);
    if (needScrollFlag) {
        [_scrollContentViewEdgeConstraint activate];
        [_scrollContentViewCenterXConstraint deactivate];
    }else {
        [_scrollContentViewEdgeConstraint deactivate];
        [_scrollContentViewCenterXConstraint activate];
    }
    
    [self.scrollView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self).insets(self.insets);
    }];
    
    UIButton *last = nil;
    for (UIButton *button in self.buttons) {
        [button mas_updateConstraints:^(MASConstraintMaker *make) {
            if (last) {
                make.left.equalTo(last.mas_right).offset(self.titleButtonSpacing);
            }else {
                make.left.equalTo(self.contentView.mas_left).offset(self.titleButtonSpacing);
            }
            
            make.top.bottom.equalTo(self.contentView);
        }];
        last = button;
    }
    
    [last mas_updateConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.contentView).offset(-self.titleButtonSpacing);
    }];
}

- (UIButton *)createButtonWithTitle:(NSString *)title {
    UIButton *button = DFMakeButton(title, nil, self.titleColor, [UIFont systemFontOfSize:15], UIButtonTypeSystem);
    return button;
}

- (void)setIndex:(NSInteger)index animated:(BOOL)animated {
    if (_indicatorCenterXConstraint) {
        [_indicatorCenterXConstraint uninstall];
    }
    
    UIButton *button = self.buttons[index];
    [self.indicatorView mas_updateConstraints:^(MASConstraintMaker *make) {
        _indicatorCenterXConstraint = make.centerX.equalTo(button);
    }];
    
    if (animated) {
        [self.contentView setNeedsUpdateConstraints];
        
        [self.contentView updateConstraintsIfNeeded];
        
        [UIView animateWithDuration:0.3 animations:^{
            [self.contentView layoutIfNeeded];
        } completion:^(BOOL finished) {
            [self scrollToIndex:index];
        }];
    }else {
        [self scrollToIndex:index];
    }
}

- (void)scrollToIndex:(NSInteger)index {
    CGRect rect = [self.contentView convertRect:self.buttons[index].frame toView:self];
//    NSLog(@"%@ %@ %@", @(CGRectGetMidX(rect)), @(self.frame.size.width), @(CGRectGetMidX(self.indicatorView.frame)));
    CGFloat bufferLength = self.scrollBufferLength?:80;
    
    if (CGRectGetMaxX(rect) + bufferLength > self.frame.size.width) {
        CGFloat x = CGRectGetMaxX(self.buttons[index].frame) - self.frame.size.width + self.titleButtonSpacing + bufferLength;
        x = (CGRectGetMaxX(self.buttons[index].frame) + self.titleButtonSpacing + bufferLength) < self.scrollView.contentSize.width ? x:(self.scrollView.contentSize.width - self.frame.size.width);
        [self.scrollView setContentOffset:CGPointMake(x, 0) animated:YES];
    }
    if (CGRectGetMinX(rect) - bufferLength < 0) {
        CGFloat x = CGRectGetMinX(self.buttons[index].frame) - self.titleButtonSpacing - bufferLength;
        x = x > 0 ? x:0;
        [self.scrollView setContentOffset:CGPointMake(x, 0) animated:YES];
    }
}

#pragma mark - setter

- (void)setTitleColor:(UIColor *)titleColor {
    _titleColor = titleColor;
    for (UIButton *button in self.buttons) {
        [button setTitleColor:_titleColor forState:UIControlStateNormal];
    }
}

- (void)setBarTintColor:(UIColor *)barTintColor {
    _barTintColor = barTintColor;
    [self.backgroundView setBarTintColor:barTintColor];
}

#pragma mark - getter

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.backgroundColor = [UIColor clearColor];
        _scrollView.showsHorizontalScrollIndicator = NO;
    }
    
    return _scrollView;
}

- (UIView *)contentView {
    if (!_contentView) {
        _contentView = [[UIView alloc] init];
    }
    
    return _contentView;
}

- (NSMutableArray<UIButton *> *)buttons {
    if (!_buttons) {
        _buttons = [[NSMutableArray alloc] init];
    }
    
    return _buttons;
}

- (UIView *)indicatorView {
    if (!_indicatorView) {
        _indicatorView = [[UIView alloc] init];
        _indicatorView.backgroundColor = [UIColor redColor];
    }
    
    return _indicatorView;
}

- (UIVisualEffectView *)visualView {
    if (!_visualView) {
        _visualView = [[UIVisualEffectView alloc] init];
    }
    
    return _visualView;
}

@end
